package top.kaoshanji.p1ch04a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 代码清单 p1ch04a-01：UTF-16的示意编码过程
 * author kaoshanji
 * ^_^
 * create time 2025/1/14 16:29
 */
public class UTF16Encoder {

    private static final Logger logger = LogManager.getLogger(UTF16Encoder.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch04a-01：UTF-16的示意编码过程...");

        UTF16Encoder encoder = new UTF16Encoder();
        System.out.println(encoder.encode(0x007A));
        System.out.println(encoder.encode(0x6C34));

        char[] result = encoder.encode(0x1F701);
        System.out.println(new String(result).length());
    }

    public char[] encode(int codePoint) {
        if ((codePoint >= 0 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) {
            return new char[]{(char) codePoint};
        } else {
            codePoint = codePoint - 0x10000;
            int high = (codePoint >> 10) + 0xD800;
            int low = (codePoint & 0x3FF) + 0xDC00;
            return new char[]{(char) high, (char) low};
        }
    }

}
